package com.kk.springboot_001.controller;

import com.kk.springboot_001.pojo.ResponseMessage;
import com.kk.springboot_001.pojo.User;
import com.kk.springboot_001.pojo.dto.UserUpdateDto;
import com.kk.springboot_001.service.MyUserDetailsService;
import com.kk.springboot_001.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

@RestController  //接口方法返回对象，转换成json文本
@RequestMapping("/user") //localhost:8089/user/**
@Slf4j
public class UserController {

    @Autowired
    UserService userService;
    @Autowired
    MyUserDetailsService userDetailsService;

    /**
     * 查询用户信息
     */
    @GetMapping("/{userId}")
    public ResponseMessage select(@PathVariable Integer userId) {
        User userNew = userService.getUser(userId);
        return ResponseMessage.success(userNew);
    }

    /**
     * 删除用户账户
     */
    @DeleteMapping("/delete-account")
    public ResponseEntity<String> deleteAccount(Authentication authentication) {
        String userName = authentication.getName();
        Integer userId = userService.getUserIdByUserName(userName);

        if (userId != null) {
            userService.delete(userId);
            return ResponseEntity.ok("账户已成功注销。");
        }

        return ResponseEntity.badRequest().body("注销失败，用户不存在。");
    }


    /**
     * 修改用户信息
     * @param updateDto
     * @return
     */
    @PostMapping("/update-info")
    public String updateUserInfo(@RequestBody UserUpdateDto updateDto) {
        // 1. 调用 Service 更新数据库信息
        User updatedUser = userService.update(updateDto);

        log.info("用户信息已更新：{}", updatedUser);
        // 2. 重新加载最新的用户信息
        UserDetails userDetails = userDetailsService.loadUserByUsername(updatedUser.getUserName());

        // 3. 创建新的 Authentication 对象
        Authentication newAuth = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());

        // 4. 更新 Spring Security 的会话信息
        SecurityContextHolder.getContext().setAuthentication(newAuth);

        // 5. 返回一个重定向路径，而不是用户对象
        return "redirect:/success";
    }

}
